package com.bw.interceptor;

import com.bw.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取浏览器发送过来的cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("token")) {
                    String token = cookie.getValue();
                    flag = JwtUtils.validToken(token);
                }
            }
        }
        if (!flag) {
            response.sendRedirect("/loginPage.do");
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
